const Message = require('../models/message');
const User = require('../models/user');
const { validationResult } = require('express-validator');

const messageController = {
    async createConversation(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { user_ids } = req.body;

        try {
            for (const user_id of user_ids) {
                const user = await User.findById(user_id);
                if (!user) {
                    return res.status(404).json({ error: `User ${user_id} not found` });
                }
            }

            const { conversation_id } = await Message.createConversation([...user_ids, req.user.user_id]);
            res.status(201).json({ conversation_id });
        } catch (error) {
            next(error);
        }
    },

    async sendMessage(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { content } = req.body;

        try {
            const { message_id } = await Message.create({
                conversation_id: req.params.conversation_id,
                user_id: req.user.user_id,
                content
            });
            res.status(201).json({ message_id });
        } catch (error) {
            next(error);
        }
    },

    async getMessages(req, res, next) {
        const { limit = 20, offset = 0 } = req.query;

        try {
            const messages = await Message.findByConversationId(
                req.params.conversation_id,
                parseInt(limit),
                parseInt(offset)
            );
            res.json(messages);
        } catch (error) {
            next(error);
        }
    }
};

module.exports = messageController;